# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

import logging
import random
from optparse import OptionParser

from cve_ease import activate_session
from cve_ease.models import CVELOG, SALOG

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def handle_smash(gconfig, db_session, args):
    """[test] Smash test tool"""
    usage = "usage: %prog smash <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-i', '--info', dest='info', default=None,
                      help='smash specific info, default is all info')
    parser.add_option('-r', '--random', dest='random', action="store_true", default=False,
                      help='smash in random mode, defulat is False')

    (options, args) = parser.parse_args(args)

    session = activate_session(db_session, gconfig)
    logger.debug(" * active sql session")

    random_string = [
        'kernel', 'openssh', 'openssl',
        'nginx', 'vim', 'java',
        'gcc', 'systemd', 'sudo',
        'audit', 'rsync', 'perl',
        'firewalld', 'kmod', 'coreutils',
        'which', 'sed', 'dbus',
        'python', 'gcc', 'glib',
        'bash', 'shadow', 'xorg',
    ]

    # for test
    # last_sa_record.securityNoticeList = last_sa_record.securityNoticeList.replace('openEuler-SA-2023-1065',
    #                                                                               'openEuler-SA-9999-8888')
    # last_sa_record.securityNoticeList = last_sa_record.securityNoticeList.replace('openEuler-SA-2023-1146',
    #                                                                               'openEuler-SA-3999-3888')
    #  cve-ease -d daemon && cve-ease -d smash -i cve  && cve-ease -d daemon
    #  cve-ease -d daemon && cve-ease -d smash -i sa && cve-ease -d daemon
    #  cve-ease -d daemon && cve-ease smash -i all -s && cve-ease -d daemon
    #  cve-ease -d daemon && cve-ease smash -i all -r && cve-ease -d daemon
    def cve_smash(random_mode=False):
        total = session.query(CVELOG).count()
        print("cve log total record :", total)
        if 0 == total:
            print(" WARN: no cve cache found! you should run 'cve-ease cve -m' to cache it.")
            return
        last_cve_record = session.query(CVELOG).order_by(CVELOG.id.desc()).first()

        new_value = last_cve_record.cveDatabaseList
        if random_mode:
            for r in random_string:
                if random.random() < 0.5:
                    logger.debug(f" * random chaneg {r} to {r.upper()}")
                    new_value = new_value.replace(r, r.upper())
        else:
            new_value = new_value.replace('openssh', 'OPENSSH')
            new_value = new_value.replace('kernel', 'KERNEL')
        if new_value == last_cve_record.cveDatabaseList:
            print(" WARN: already smashed! you may add -r to random smash it.")
            return

        last_cve_record.cveDatabaseList = new_value
        session.commit()
        print("cve latest log smash done!")

    def sa_smash(random_mode=False):
        total = session.query(SALOG).count()
        print("sa log total record :", total)
        if 0 == total:
            print(" WARN: no sa cache found! you should run 'cve-ease sa -m' to cache it.")
            return
        last_sa_record = session.query(SALOG).order_by(SALOG.id.desc()).first()

        new_value = last_sa_record.securityNoticeList
        if random_mode:
            for r in random_string:
                if random.random() < 0.5:
                    logger.debug(f" * random chaneg {r} to {r.upper()}")
                    new_value = new_value.replace(r, r.upper())
        else:
            new_value = new_value.replace('openssh', 'OPENSSH')
            new_value = new_value.replace('kernel', 'KERNEL')
        if new_value == last_sa_record.securityNoticeList:
            print(" WARN: already smashed! you may add -r to random smash it.")
            return

        last_sa_record.securityNoticeList = new_value
        session.commit()
        print("sa latest log smash done!")

    if options.info:
        if "cve" == options.info:
            cve_smash(options.random)
        elif "sa" == options.info:
            sa_smash(options.random)
        else:
            cve_smash(options.random)
            sa_smash(options.random)
        print(" do smash done!")
    else:
        parser.print_help()
